import Spirit from "./spirit.js"

class SpiritUtils {
    constructor(game) {
        this.game = game;
    }

    draw_spirit() {
        let game = this.game;

        let spirit_list = game.game_info.spirit_list;

        for (let i = 0; i < spirit_list.length; i++) {
            spirit_list[i].draw();
        }
    };

    clear_canvas() {
        let game = this.game;
        let map = game.map;
        let ctx = game.stage_canvas_ctx;
        let {width, height} = map.map_info;

        ctx.clearRect(0, 0, width, height);

    };

    gen_spirit() {
        let spirit_list = this.game.game_info.spirit_list;
        this.spirit_gen_ts = this.spirit_gen_ts || 0;
        let ts = new Date().getTime();
        let gen_interval = this.game.config.spirit.gen_interval;

        if (spirit_list.length < this.game.config.spirit.max_live_spirit) {
            if (ts - this.spirit_gen_ts > gen_interval) {
                if (Math.random() > 0.5) {
                    let spirit_types = this.game.config.spirit_types;
                    let r2 = (Math.random() * spirit_types.length) | 0;
                    let spirit_config = spirit_types[r2];

                    let spirit = new Spirit(this.game, spirit_config);
                    this.game.game_info.spirit_count++;
                    this.game.game_info.blood_amount += spirit.blood;

                    let last_spirit = spirit_list[spirit_list.length - 1];
                    if (!last_spirit || last_spirit.row !== 0 && last_spirit.col !== 0) {
                        spirit_list.push(spirit);
                    }
                }
                this.spirit_gen_ts = ts;
            }
        }
    };

    spirit_move() {
        let spirit_list = this.game.game_info.spirit_list;

        for (let i = 0; i < spirit_list.length; i++) {
            spirit_list[i].move_on();
        }
    };

    cls_spirit() {
        let spirit_list = this.game.game_info.spirit_list;

        for (let i = spirit_list.length - 1; i >= 0; i--) {
            let spirit = spirit_list[i];
            if (spirit.blood <= 0) {
                spirit_list.splice(i, 1);
                if (!spirit.lost) {
                    let gold = spirit.config.gold;
                    this.game.game_info.gold += gold;
                }
            }
        }
    };

    has_spirit_on_cell(row, col) {
        let spirit_list = this.game.game_info.spirit_list;

        for (let i = spirit_list.length - 1; i >= 0; i--) {
            let spirit = spirit_list[i];
            let map_cell = spirit.cur_map_cell;

            if (map_cell && map_cell.row === row && map_cell.col === col) {
                return true;
            }

            map_cell = spirit.next_map_cell;
            if (map_cell && map_cell.row === row && map_cell.col === col) {
                return true;
            }
        }
    };
}

export default SpiritUtils;